/**
 *
 */
package uy.edu.um.taller2;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

/**
 * @author pegardan
 *
 */
public class JDBCTest {

	private Logger log = Logger.getLogger(JDBCTest.class);

	public void insertClient() {
		Connection oConnection = null;

		log.info("Agregando Clientes");

		try {

			oConnection = ConnectionMgr.getInstance().getConnection();

			Statement oStatement = oConnection.createStatement();

			oStatement.execute("INSERT INTO CLIENTES VALUES (2, 'Jose', 'Pereda')");

			oStatement.close();

		} catch (Exception e) {

			throw new RuntimeException(e);

		} finally {

			if (oConnection != null) {

				try {

					oConnection.close();

				} catch (SQLException e) {

					log.error(e);
					throw new RuntimeException(e);
				}

			}

		}

	}

	public void getClients() {
		Connection oConnection = null;

		log.info("Obteniendo Clientes");

		try {

			oConnection = ConnectionMgr.getInstance().getConnection();

			Statement oStatement = oConnection.createStatement();

			ResultSet oResultSet = oStatement.executeQuery("SELECT * FROM CLIENTES");

			while (oResultSet.next()) {

				int nId = oResultSet.getInt(1);
				String sName = oResultSet.getString(2);
				String sApellido = oResultSet.getString(3);

				System.out.println("Cliente. ID: " + nId + " Nombre: " + sName + " Apellido: " + sApellido);

			}

			oResultSet.close();
			oStatement.close();

		} catch (SQLException e) {

			throw new RuntimeException(e);

		} finally {

			if (oConnection != null) {

				try {
					oConnection.close();
				} catch (SQLException e) {

					throw new RuntimeException(e);
				}

			}

		}

	}


	public static void main(String[] args) {

		JDBCTest oTest  = new JDBCTest();

		try {

			oTest.insertClient();

			oTest.getClients();

		} finally {

			try {

				ConnectionMgr.getInstance().closeDatasource();

			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}


	}

}
